import 'package:flutter/material.dart';
import 'package:magic_car/authinspcter/commonwidget/my_app_bar.dart';
import 'package:magic_car/authinspcter/commonwidget/my_muti_selector.dart';
import 'package:magic_car/authinspcter/commonwidget/my_scroll_view.dart';
import 'package:magic_car/res/resources.dart';
import 'package:magic_car/util/colors.dart';

class SubmitAuthcarPage extends StatefulWidget {
  const SubmitAuthcarPage({Key key, this.type}) : super(key: key);

  final int type;

  @override
  _ExpressPageState createState() => _ExpressPageState();
}

class _ExpressPageState extends State<SubmitAuthcarPage>
    with SingleTickerProviderStateMixin {
  var modelinfo;
  String provincename = "";
  String cityname = "";
  String areaname = "";
  String areaStr = "";
  TextEditingController colorController = new TextEditingController();
  TextEditingController priceController = new TextEditingController();
  TextEditingController tccontactController = new TextEditingController();
  TextEditingController jccontactController = new TextEditingController();
  TextEditingController remarkController = new TextEditingController();
  TextEditingController zydnameController = new TextEditingController();
   TextEditingController jccontactmobController = new TextEditingController();
  TextEditingController tccontactmobController = new TextEditingController();
  

  List taocan_arr = [
    {"title": "需要", "select": false, "fanli": "0", "value": 1},
    {"title": "不需要", "select": false, "fanli": "0", "value": 0}
  ];
  List expresstype = [
     {"title": "板车", "select": true, "fanli": "0", "value": 1},
    {"title": "地跑", "select": false, "fanli": "0", "value": 0}
  ];
  //int dianzitype = 0;
  List input_data = [
    {
      "type": 1,
      "title": "车型详情",
      "photo": false,
      "value": "奥迪A3 219年款",
      "code": "car"
    },
    {
      "type": 2,
      "title": "颜色",
      "photo": false,
      "place_str": "请准确填写",
      "typeboard": TextInputType.text,
      "code": "color"
    },
    {
      "type": 2,
      "title": "价格",
      "photo": false,
      "place_str": "120000",
      "typeboard": TextInputType.number,
      "code": "price"
    },
    {
      "type": 2,
      "title": "资源店名称",
      "photo": false,
      "place_str": "资源店名称",
      "typeboard": TextInputType.text,
      "code": "zyd"
    },
    {
      "type": 1,
      "title": "提车位置",
      "photo": false,
      "value": "请选择提车位置",
      "code": "address"
    },
    // {"type": 1, "title": "接车位置", "photo": false, "value": "昆明盘龙区白云路麦苗云车店"},
    {
      "type": 2,
      "title": "提车联系人",
      "photo": false,
      "value": "小杨  18945678943",
      "place_str": "提车联系人",
      "typeboard": TextInputType.text,
      "code": "tc"
    },
    {
      "type": 2,
      "title": "提车联系方式",
      "photo": false,
      "value": "小杨  18945678943",
      "place_str": "提车联系方式",
      "typeboard": TextInputType.phone,
      "code": "tc_mob"
    },
    {
      "type": 2,
      "title": "接车联系人",
      "photo": false,
      "place_str": "接车联系人及联系方式",
      "typeboard": TextInputType.text,
      "code": "jc"
    },
    {
      "type": 2,
      "title": "接车联系人",
      "photo": false,
      "place_str": "接车联系方式",
      "typeboard": TextInputType.phone,
      "code": "jc_mob"
    },
    // {"type": 3, "title": "运输价格", "photo": false},
    {
      "type": 4,
      "title": "电子合同",
      "photo": true,
    }
  ];

  int dianzibool = 0;
  List moneyphotos=[];
  int expresstypeindex= 1;
  


  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
        backgroundColor: Colours.base_page_color,
        appBar:new AppBar(
          elevation: 0,
          backgroundColor: Colors.white,
          title:Text("添加车源信息",style:TextStyle(fontSize:16)),
        ),
        // appBar: MyAppBar(
        //   centerTitle: "添加车源",
        // ),
        body: Container(
            padding: new EdgeInsets.fromLTRB(10, 10, 10, 0),
            child: MyScrollView(children: [
              Gaps.vGap10,
              inputdata(),
              Gaps.vGap24,
              handWidget()
            ])));
  }

  // Widget topImg() {
  //   return Container(
  //     child: LoadAssetImage("bjcar/jinronglog"),
  //   );
  // }

  submit() {
    if(modelinfo==null){
    // Toast.show("请选择车辆信息");
     return;
    }
    Map<String, String> map = new Map();
    map["model_id"] = modelinfo["id"].toString();
    map["shop_name"] = zydnameController.text;
    map["color"] = colorController.text;
    map["car_price"] = priceController.text;
    map["ti_province_name"] = provincename;
    map["ti_city_name"] = cityname;
    map["ti_area_name"] = areaname;
    map["jie_mobile"] = jccontactmobController.text;
    map["ti_mobile"] = tccontactmobController.text;
    map["ti_name"] = tccontactController.text;
    map["jie_name"] = jccontactController.text;
    map["is_dianzi"] = dianzibool.toString();
    map["remake"] = remarkController.text;
    map["type"] = expresstypeindex.toString();
    

    // for (var item in taocan_arr) {
    //   if (item["select"] == true) {
    //     map["dianzi"] = item["value"].toString();
    //   }
    // }
    print("提交的参数$map");

    // HttpHelper.postRequest(HttpHelper.crateexpressorder, true, true, context,
    //     (data) async {
    //   if (data != null) {
    //     if (data["code"].toString() == "1") {
    //       // Toast.show(data["message"]);
    //       _showConfirmDialog();
    //     }
    //   }
    // }, params: map);
  }

  void _showConfirmDialog() {
    // showDialog<bool>(
    //         context: context,
    //         barrierDismissible: false,
    //         builder: (_) => MyalertBorderDialog("温馨提示", "我们已经收到了你提交的订单，请等待审核。"))
    //     .then((value) {
    //   if (value == true) {
    //     // Toast.show("提交成功");
    //     NavigatorUtils.goBack(context);
    //   }
    // });
  }

  Widget handWidget() {
    return Container(
      child: Row(children: [
        Expanded(
          child: GestureDetector(
              onTap: () {
                submit();
                //Toast.show("正在开发。。。");
              },
              child: Container(
                  padding: new EdgeInsets.only(top: 10, bottom: 10),
                  decoration: BoxDecoration(
                      color: Colours.app_main,
                      borderRadius: BorderRadius.circular(4)),
                  child: Center(
                      child: Text("提交",
                          style:
                              TextStyle(fontSize: 18, color: Colors.white))))),
        )
        // Gaps.hGap10,
        // Expanded(child: Container(
        //   padding: new EdgeInsets.only(top:10,bottom:10),
        //   decoration: BoxDecoration(
        //     color:Colours.dark_app_main,
        //     borderRadius: BorderRadius.circular(4)
        //   ),
        //   child:Center(child:Text("核价",style: TextStyle(fontSize:18,color: Colors.white),))
        // )),
      ]),
    );
  }

  Widget inputdata() {
    List<Widget> tiles = [];
    for (int i = 0; i < input_data.length; i++) {
      if(i==input_data.length-1){
        tiles.add(expresstypewidget());
      }
      tiles.add(ensurenInputItem(input_data[i]));
      tiles.add(Gaps.line);
    }
    tiles.add(dianzi());
    tiles.add(Gaps.line);
    tiles.add(remark());
    return Container(
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(4.0),
      ),
      child: Column(children: tiles),
    );
  }
 Widget remark(){
    return Container(
        width: MediaQuery.of(context).size.width - 20,
        padding: new EdgeInsets.only(left: 10, right: 10, top: 10, bottom: 10),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(4.0),
        ),
        child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
          Container(
            child: Text("备注"),
          ),
          Gaps.vGap10,
          Container(
              child: 
              TextField(
        
        controller: remarkController,
        maxLines: 3,
        decoration: InputDecoration(
            border: InputBorder.none, hintText: "填写备注"),
      )
              )
        ]));
 }
 Widget expresstypewidget(){
 return Container(
        width: MediaQuery.of(context).size.width - 20,
        padding: new EdgeInsets.only(left: 10, right: 10, top: 10, bottom: 10),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(4.0),
        ),
        child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
          Container(
            child: Text("运输方式"),
          ),
          Gaps.vGap10,
          Container(
              child: Wrap(
            spacing: 2,
            runSpacing: 10,
            children: menuitem(expresstype)
          )),
         
        ]));
 }
  Widget dianzi() {
    return Container(
        width: MediaQuery.of(context).size.width - 20,
        padding: new EdgeInsets.only(left: 10, right: 10, top: 10, bottom: 10),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(4.0),
        ),
        child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
          Container(
            child: Text("是否需要平台垫资"),
          ),
          Gaps.vGap10,
          Container(
              child: Wrap(
            spacing: 2,
            runSpacing: 10,
            children: menuitem(taocan_arr),
          )),
          // Offstage(
          //   offstage: dianzibool==1?false:true,
          //   child:Gaps.vGap8
          // ),
          // Offstage(
          //   offstage: dianzibool==1?false:true,
          //   child:Text("请上传垫资意向金打款凭证"),
          // ),
          // Offstage(
          //   offstage: dianzibool==1?false:true,
          //   child:_buildMediaView("1", [])
          // )
        ]));
  }
  //创建媒体文件展示视图
  Widget _buildMediaView(code, data) {
    List<Widget> tiles = [];
    Widget content;
    List temp = [];
    // if (show == 0) {
    // } else if (show == 1) {
    //   temp = data;
    // }
    temp = moneyphotos;
   

    for (int i = 0; i < temp.length; i++) {
      var imgitems = temp[i];
      if (imgitems.length == 0) {
        temp.removeAt(i);
        continue;
      }
      tiles.add(Padding(
          padding: new EdgeInsets.fromLTRB(5, 15, 5, 10),
          child: Container(
              decoration: BoxDecoration(color: Colours.base_page_color),
              child: Stack(children: [
                GestureDetector(
                    onTap: () {
                      // if(files[i]["type"]==1){
                      //   editfile();
                      // }
                      // Navigator.of(context).push(new FadeRoute(
                      //     page: GalleryPhotoViewWrapper(
                      //   galleryItems: imageModel(temp),
                      //   backgroundDecoration: const BoxDecoration(
                      //     color: Colors.black,
                      //   ),
                      //   initialIndex: i,
                      // )));
                    },
                    child: Container(
                        padding: new EdgeInsets.only(top: 10),
                        child: Image.network(
                          temp[i]["url"],
                          width: 100,
                          height: 100,
                        ))),
                Positioned(
                    right: -14,
                    top: -15,
                    child: IconButton(
                        icon: Icon(
                          Icons.delete_outlined,
                          size: 20,
                          color: Colors.red,
                        ),
                        onPressed: () {
                          _showDialog(i, temp);
                        }))
              ]))));
    }
    // if (temp.leng == 0) {
    tiles.add(Padding(
      padding: new EdgeInsets.fromLTRB(5, 15, 0, 10),
      child: GestureDetector(
          onTap: () {
            // selelctphoto();
            _showPhotoWidget(code);
          },
          child:Container())
        //  child: LoadAssetImage("bjcar/upimg", width: 100, height: 100)),
    ));
    //}
    content = new Wrap(children: tiles);
    return content;
  }

  void _showDialog(index, data) {
    // showDialog<bool>(
    //         context: context,
    //         builder: (_) => MyalertDialog(title: "提示", message: "确定删除图片？"))
    //     .then((value) {
    //   if (value == true) {
    //     deleteimg(index, data);
    //   }
    // });
  }

  //删除图片
  deleteimg(index, dataArr) {
    Map<String, String> map = new Map();
    map["ids"] = dataArr[index]["id"].toString();
    // map["page"] = page.toString();
    // map["audit"] = audit.toString();
    // HttpHelper.postRequest(HttpHelper.deleteimg, true, true, context,
    //     (data) async {
    //   if (data != null) {
    //     if (data["code"].toString() == "1") {
    //       dataArr.removeAt(index);
    //       setState(() {
    //         dataArr = dataArr;
    //         // deleteimgid = temp[i]["id"].toString();
    //       });
    //     }
    //   }
    // }, params: map);
  }

  List imageModel(data) {
    List img_temp = [
      "https://car3.autoimg.cn/cardfs/product/g1/M09/3F/A8/240x180_0_q95_c42_autohomecar__ChwFqV69W4KAf_AzAAShphUBgV4514.jpg",
      "https://car2.autoimg.cn/cardfs/product/g25/M09/6E/D2/240x180_0_q95_c42_autohomecar__ChwFj169W32Ad5ehAAT2abQFAio994.jpg",
      "https://car2.autoimg.cn/cardfs/product/g25/M08/6E/D2/240x180_0_q95_c42_autohomecar__ChwFj169W3uATe71AASA9ZdptWg816.jpg",
      "https://car2.autoimg.cn/cardfs/product/g25/M0B/73/06/240x180_0_q95_c42_autohomecar__ChsEmF69W3qAYeneAAQeve0abAo167.jpg",
    ];
    List imgList = List();
    // for (int x = 0; x < data.length; x++) {
    //   GalleryExampleItem item = GalleryExampleItem();
    //   item.id = '$x';
    //   item.resource = data[x]["url"];
    //   imgList.add(item);
    // }
    // print(imgList.first.id);

    return imgList;
  }

  //弹出图片选择插件
  _showPhotoWidget(code) {
    // showModalBottomSheet(
    //     context: context,
    //     builder: (BuildContext context) {
    //       return Selectphoto(1, (data) {
    //         //uploadImg(data);
    //         print("图片返回结果${data}");
    //         moneyphotos.add(data["data"]);
    //         setState(() {
    //           moneyphotos = moneyphotos;
    //         });
           
    //       });
    //     });
  }

  List<Widget> menuitem(data) {
    print(data);
    List<Widget> tiles = [];
    for (int i = 0; i < data.length; i++) {
      tiles.add(Container(
        padding: EdgeInsets.only(left: 1, top: 5, right: 10, bottom: 5),
        child: ChoiceChipWidget(
          boxSelectColor: Colours.app_main,
          textSelectColor: Colors.white,
          selectBorder: Border.fromBorderSide(BorderSide(
              color: Colours.app_main, width: 1, style: BorderStyle.solid)),
          boxColor: Colours.base_gray,
          textColor: Colours.text_gray,
          // selectBorder: bod,
          height: 34,

          text: data[i]["title"],
          fontSize: 12,
          selected: data[i]["select"],
          border: Border.fromBorderSide(BorderSide(
              color: Colours.base_page_color,
              width: 1,
              style: BorderStyle.solid)),

          onSelected: (selected) {
            int selectnum = 0;
            for (int k = 0; k < data.length; k++) {
              if (k != i) {
                data[k]["select"] = false;
              }
              // if (taocan_arr[i]["select"] == true) selectnum++;
            }
            // if (selectnum > 2 && data[i]["select"] == false) {
            //   Toast.show("最多选择三个");
            //   return;
            // }
            data[i]["select"] = !data[i]["select"];
            if (data[i]["select"]) {
              //选中的时候进行数据处理
             
            }
            if(data==taocan_arr){
            setState(() {
              taocan_arr = taocan_arr;
              dianzibool = i+1;
              // currntProduct = data[i];
            });
            }else {
              setState(() {
                expresstype = data;
                expresstypeindex = i+1;
              });
            }

            
          },
        ),
      ));
    }
    return tiles;
  }

  Widget ensurenInputItem(data) {
    // if(data["type"] == 1){
    //   return Container(
    //     child: Row(
    //       chi
    //     ),
    //   );
    // }
    List<Widget> tiles = [];

    Widget title = Container(
        padding: new EdgeInsets.only(top: 14),
        height: 40,
        width: 110,
        child: Text(
          data["title"],
          
        ));
    tiles.add(title);
    tiles.add(Gaps.hGap10);

    if (data["type"] == 1) {
      tiles.add(GestureDetector(
          onTap: () async {
            if (data["code"] == "car") {
              //选择车型
              // Navigator.of(context).push(new MaterialPageRoute(builder: (_) {
              //   return new SelectBrandPage(type: 2);
              // })).then((param) {
              //   print("车系最终返回值${param}");
              //   setState(() {
              //     modelinfo = param;
              //     data["value"] = param["name"];
              //   });
              // });
            } else if (data["code"] == "address") {
              //选择提车位置
              // FocusScope.of(context).requestFocus(FocusNode());
              // final result = await KzcityPicker.showPicker(context);

              // if (result != null) {
              //   setState(() {
              //     provincename = result.province;
              //     cityname = result.city;
              //     areaname = result.area;

              //     areaStr = "${result.city}/${result.area}";
              //     data["value"] = areaStr;
              //   });
              // }
            }
          },
          child: Text(
            data["value"],
            style: TextStyle(fontSize: 12),
          )));
    }
    if (data["type"] == 2) {
      TextEditingController temp = new TextEditingController();
      if (data["code"] == "color") {
        temp = colorController;
      } else if (data["code"] == "price") {
        temp = priceController;
      } else if (data["code"] == "tc") {
        temp = tccontactController;
      } else if (data["code"] == "jc") {
        temp = jccontactController;
      }else if(data["code"]=="zyd"){
        temp = zydnameController;
      }else if(data["code"]=="tc_mob"){
         temp = tccontactmobController;
      }else if(data["code"]=="jc_mob"){
        temp = jccontactmobController;
      }
      tiles.add(Expanded(
          child: Container(
           
        child: TextField(
          style: TextStyle(fontSize: 14),
        keyboardType: data["typeboard"],
        controller: temp,
        decoration: InputDecoration(
            border: InputBorder.none, hintText: data["place_str"]),
      )
      )));
      if (data["photo"]) {
        // tiles.add(Container(
        //   child: LoadAssetImage("bjcar/carema", width: 20, height: 20),
        // ));
      }
    }
    if (data["type"] == 3) {
      tiles.add(Expanded(
          child: Container(
        child: Align(
            alignment: Alignment.centerRight,
            child: new Text(
              "360.00",
              style: TextStyle(fontSize: 14, color: Colours.base_app_price),
            )),
      )));

      // if(data["photo"]){
      //   tiles.add(
      //     Container(
      //       child: LoadAssetImage("bjcar/carema",width: 20,height:20),
      //     )
      //   );
      // }
    }
    if (data["type"] == 4) {
      tiles.add(Expanded(
          child: Container(
        child: Align(
            alignment: Alignment.centerRight,
            child: new Text(
              "下单后查看",
              style: TextStyle(fontSize: 14, color: Colours.dark_app_main),
            )),
      )));
    }
    return Container(
      padding: new EdgeInsets.only(left: 10, right: 10),
      child: Row(
        children: tiles,
      ),
    );
  }
}
